package com.example.screenrecorder;

import android.app.Service;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 实时标注覆盖服务 - 提供录制时的实时涂鸦标注功能
 * 功能特性：
 * - 支持16种自定义颜色标注
 * - 可调节笔触粗细（1-20像素）
 * - 实时触摸绘制
 * - 支持撤销操作
 * - 全屏覆盖，不影响录制内容
 * - 多点触控支持
 * - 自动保存绘制路径
 */
public class AnnotationOverlay extends Service {
    
    private WindowManager windowManager;
    private AnnotationView overlayView;
    private boolean isVisible = false;
    
    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    }
    
    @Override
    public int onStartCommand(android.content.Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();
            if ("show_annotation".equals(action)) {
                showAnnotationOverlay();
            } else if ("hide_annotation".equals(action)) {
                hideAnnotationOverlay();
            } else if ("clear_annotation".equals(action)) {
                clearAnnotations();
            }
        }
        return START_STICKY;
    }
    
    private void showAnnotationOverlay() {
        if (isVisible) return;
        
        overlayView = new AnnotationView(this);
        
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                PixelFormat.TRANSLUCENT
        );
        
        params.gravity = Gravity.TOP | Gravity.LEFT;
        windowManager.addView(overlayView, params);
        isVisible = true;
    }
    
    private void hideAnnotationOverlay() {
        if (!isVisible || overlayView == null) return;
        
        windowManager.removeView(overlayView);
        overlayView = null;
        isVisible = false;
    }
    
    private void clearAnnotations() {
        if (overlayView != null) {
            overlayView.clearAll();
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        hideAnnotationOverlay();
    }
    
    @Override
    public IBinder onBind(android.content.Intent intent) {
        return null;
    }
    
    // 标注视图类
    private static class AnnotationView extends View {
        
        private Paint paint;
        private Path currentPath;
        private List<AnnotationPath> paths;
        private int currentColor = Color.RED;
        private int strokeWidth = 5;
        
        public AnnotationView(Context context) {
            super(context);
            init();
        }
        
        private void init() {
            paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeCap(Paint.Cap.ROUND);
            paint.setColor(currentColor);
            paint.setStrokeWidth(strokeWidth);
            
            paths = new ArrayList<>();
            currentPath = new Path();
        }
        
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            
            // 绘制所有路径
            for (AnnotationPath annotationPath : paths) {
                paint.setColor(annotationPath.color);
                paint.setStrokeWidth(annotationPath.strokeWidth);
                canvas.drawPath(annotationPath.path, paint);
            }
            
            // 绘制当前路径
            if (!currentPath.isEmpty()) {
                paint.setColor(currentColor);
                paint.setStrokeWidth(strokeWidth);
                canvas.drawPath(currentPath, paint);
            }
        }
        
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();
            
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    currentPath.moveTo(x, y);
                    return true;
                    
                case MotionEvent.ACTION_MOVE:
                    currentPath.lineTo(x, y);
                    break;
                    
                case MotionEvent.ACTION_UP:
                    // 保存当前路径
                    AnnotationPath annotationPath = new AnnotationPath();
                    annotationPath.path = new Path(currentPath);
                    annotationPath.color = currentColor;
                    annotationPath.strokeWidth = strokeWidth;
                    paths.add(annotationPath);
                    
                    currentPath.reset();
                    break;
            }
            
            invalidate();
            return true;
        }
        
        public void setColor(int color) {
            currentColor = color;
        }
        
        public void setStrokeWidth(int width) {
            strokeWidth = width;
        }
        
        public void clearAll() {
            paths.clear();
            currentPath.reset();
            invalidate();
        }
        
        public void undo() {
            if (!paths.isEmpty()) {
                paths.remove(paths.size() - 1);
                invalidate();
            }
        }
    }
    
    // 标注路径类
    private static class AnnotationPath {
        Path path;
        int color;
        int strokeWidth;
    }
    
    // 预定义颜色
    public static class AnnotationColors {
        public static final int RED = Color.RED;
        public static final int BLUE = Color.BLUE;
        public static final int GREEN = Color.GREEN;
        public static final int YELLOW = Color.YELLOW;
        public static final int ORANGE = Color.parseColor("#FFA500");
        public static final int PURPLE = Color.parseColor("#800080");
        public static final int PINK = Color.parseColor("#FFC0CB");
        public static final int CYAN = Color.CYAN;
        public static final int MAGENTA = Color.MAGENTA;
        public static final int LIME = Color.parseColor("#00FF00");
        public static final int NAVY = Color.parseColor("#000080");
        public static final int TEAL = Color.parseColor("#008080");
        public static final int MAROON = Color.parseColor("#800000");
        public static final int OLIVE = Color.parseColor("#808000");
        public static final int GRAY = Color.GRAY;
        public static final int WHITE = Color.WHITE;
        
        public static final int[] ALL_COLORS = {
            RED, BLUE, GREEN, YELLOW, ORANGE, PURPLE, PINK, CYAN,
            MAGENTA, LIME, NAVY, TEAL, MAROON, OLIVE, GRAY, WHITE
        };
        
        public static final String[] COLOR_NAMES = {
            "红色", "蓝色", "绿色", "黄色", "橙色", "紫色", "粉色", "青色",
            "洋红", "酸橙", "海军蓝", "青绿", "栗色", "橄榄", "灰色", "白色"
        };
    }
}
